import time

import requests
from lxml import etree
from selenium import webdriver

from xiami.kaisha import str2url


def get_page():
    browser = webdriver.Chrome()  # 打开Chrome
    url = 'https://emumo.xiami.com/chart'
    browser.get(url)
    time.sleep(3)  # 等待页面加载
    html = browser.page_source  # 浏览器渲染后的页面
    return html


def get_resource(url):
    """获取二进制资源文件(图片，mp3, 视频)"""
    headers = {
        "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36"
    }
    response = requests.get(url, headers=headers)
    if response.status_code == 200:
        # response.content返回的是字节流，decode后变成字符串
        return response.content
    return None


def save_mp3(mp3_url, title):
    mp3_content = get_resource(mp3_url)
    with open(f'./mp3/{title}.mp3', 'wb') as f:
        f.write(mp3_content)


def parse_page(html):
    etree_html = etree.HTML(html)
    res = etree_html.xpath('//tr[@class="songwrapper"]')
    for item in res:
        data_mp3 = item.xpath('./@data-mp3')[0]
        data_title = item.xpath('./@data-title')[0]
        print(data_title)
        # print(data_mp3)
        mp3_url = str2url(data_mp3)  # 凯撒解密获取MP3地址
        print(mp3_url)
        # save_mp3(mp3_url, data_title)


def main():
    html = get_page()
    parse_page(html)
    # print(html)


if __name__ == '__main__':
    main()
